package com.xpalive.utils.beans;

import com.xpalive.commons.StringPool;
import com.xpalive.exception.BizException;
import com.xpalive.utils.lambda.XFieldNameFunction;
import com.xpalive.utils.lambda.XLambdaUtils;
import java.lang.reflect.Field;
import lombok.Data;

@Data
public class BeanDefVal<T> {

    private final T t;

    public <R> BeanDefVal<T> defIfNull(XFieldNameFunction<T, R> lambda, R r) {
        String fieldName = XLambdaUtils.getFieldName(lambda);
        R result = lambda.apply(t);
        if (result == null) {
            setFieldVal(fieldName, r);
        }
        return this;
    }


    public BeanDefVal<T> defIfBlank(XFieldNameFunction<T, String> lambda, String r) {
        String fieldName = XLambdaUtils.getFieldName(lambda);
        String result = lambda.apply(t);
        if (result == null
            || result.trim().equals(StringPool.EMPTY)) {
            setFieldVal(fieldName, r);
        }
        return this;
    }

    private <R> void setFieldVal(String fieldName, R r) {
        Class<?> tClass = t.getClass();
        try {
            Field field = XBeanUtils.getDeclaredField(tClass, fieldName);
            field.setAccessible(true);
            field.set(t, r);
        } catch (ReflectiveOperationException e) {
            throw BizException.of("Could not set property '" + fieldName
                + "' value of '" + r + "'", e);
        }
    }
}
